package com.myjoje.config.shiro;

import com.myjoje.base.BaseUtil;
import com.myjoje.bean.UserBean;
import com.myjoje.service.system.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 自定义realm
 */
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取用户信息
        UserBean bean  = (UserBean) principals.getPrimaryPrincipal();
        //角色ids
        String roleIds = bean.getRoleIds();
        List roleList = new ArrayList();
        if (BaseUtil.isNotEmpty(roleIds)) {
            roleList = Arrays.asList(roleIds.split(","));
        }
        String permissionIds = bean.getPermissionIds();
        List permissionList = new ArrayList();
        if (BaseUtil.isNotEmpty(permissionIds)) {
            permissionList = Arrays.asList(permissionIds.split(","));
        }
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addRoles(roleList);
        authorizationInfo.addStringPermissions(permissionList);
        return authorizationInfo;
    }

    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String principal = (String) token.getPrincipal();
        UserBean bean = userService.findUserByPrincipal(principal);
        if (null == bean) {
            return null;
        } else {
            //微信登录使用openid，不验证密码
            if (principal.equals(bean.getOpenid())) {
                return new SimpleAuthenticationInfo(bean, ShiroUtil.getMd5("123"), this.getName());
            }
            return new SimpleAuthenticationInfo(bean, bean.getPassword(), this.getName());
        }
    }
}
